package cn.edu.scnu.pay.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 用于获取bean对象
 */
@Component
public class SpringUtils implements ApplicationContextAware {
    private static final Logger LOGGER = LoggerFactory.getLogger(SpringUtils.class);

    private static ApplicationContext APP_CONTEXT;

    public static ApplicationContext getApplicationContext() {
        return APP_CONTEXT;
    }

    @Override
    public void setApplicationContext(ApplicationContext appContext) throws BeansException {
        APP_CONTEXT = appContext;
    }

    /**
     * 获取容器中的Bean对象
     *
     * @param beanId
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String beanId) {

        if (null == APP_CONTEXT) {
            return null;
        }

        return (T) APP_CONTEXT.getBean(beanId);
    }
}